<?php
/**
 * Created by PhpStorm.
 * User: lyw
 * Date: 2016/5/26
 * Time: 9:40
 */
include_once ADMIN_PATH ."../bs/bs.automation.php";
class Video_courseController extends BaseController {
    public function index(){
        $doVideo = new Do语音课程();
        $doUser = new Do用户();
        $doComment = new DoStatistic();
        $doChat = new Do群聊();
        $count = $doVideo->where("type='视频'")->count();
        $page = new \tools\Page($count,15);
        $videoCourses = $doVideo->fields("a.*,b.name,count(c.tid) as comment_num")
            ->offset($page->limit)
            ->limit($page->pagesize)
            ->leftJoin($doUser,'b','a.讲课专家id=b.id')
            ->leftJoin($doComment,'c','a.id=c.tid and c.type=2')
            ->where("a.type='视频'")
            ->groupby('a.id')
            ->orderby('a.id desc')
            ->rows();
        foreach($videoCourses as $k=>$v)
        {
            $doSignUp = new Do语音课程报名();
            $num = $doSignUp->fields('count(b.id)')->leftJoin($doUser,'b','a.用户id=b.id')
                ->where("a.课程id=".$v['id']." and a.状态='报名'")
                ->getOneField();
            $videoCourses[$k]['num'] = $num;

            $doGroup = new Do群离线();
            $online_num = $doGroup->where("群id=".$v['群id'])->count();
            $videoCourses[$k]['online_num'] = $online_num;
            $doGroup = new Do群离线();
            $time = date("Y-m-d H:i:s", time()-10);
            $real_time_online = $doGroup->where("群id=".$v['群id']." and 最后在线时间 > '$time'")->count();
            $videoCourses[$k]['real_time_online'] = $real_time_online;

            $chat_num = $doChat->where("群id=".$v['群id'])->count();
            $videoCourses[$k]['chat_num'] = $chat_num;
        }
        require $this->template;

    }
    public function addVideo(){
        $doVideo = new Do语音课程();
        $doUser = new Do用户();
        $doDoctor = new Do医师详情();
        $id = $this->request('id');
        if($id)
        {
            $videoCourse = $doVideo->fields("a.*,b.name,c.医院")
                ->leftJoin($doUser,'b','a.讲课专家id=b.id')
                ->leftJoin($doDoctor,'c','b.id=c.用户id')
                ->where("a.id=".$id)->row();
            $course = $videoCourse->data;
        }

        $doSign = new DoCourse_sign();
        $signList = $doSign->rows();
        require $this->template;
    }

    public function addVideo_post(){
        $id = $this->request('id');
        $title = $this->request('title','',true);
        $content = $this->request('content','',true);
        $stime = $this->request('开始时间');
        $etime = $this->request('结束时间');
        $expertId = $this->request('专家id','',true);
        $chatId = $this->request('chatId','');
        $sign_id = $this->request('sign_id', '');

        $bm = new C后台管理员();
        $res = $bm->fc判断当前时间内专家有课($expertId,$stime,$etime,$id);
        if($res>0) {
            exit("<script>alert('该专家已有安排');</script>");
        }

        pdo()->beginTransaction();
        #建群
        $groupId = true;
        if (!$id) {
            $groupId = $this->create_course_group($expertId);
        }

        #建课程
        $doVideo = new Do语音课程();
        if ($id) {
            $doVideo->set_id($id);
        } else {
            global $G_CONFIG;
            $doVideo->set_群id($groupId);
            if(!$G_CONFIG['模板消息ID']['课程提醒']){
                echo "<script>alert('课程提醒ID不能为空');</script>";
                return;
            }
            if(!$G_CONFIG['模板消息ID']['课程开课通知']){
                echo "<script>alert('课程开课通知ID不能为空');</script>";
                return;
            }
            $doVideo->set_咨询模板ID(trim($G_CONFIG['模板消息ID']['课程提醒']));
            $doVideo->set_course_notice_templateId($G_CONFIG['模板消息ID']['课程开课通知']);
        }
        $doVideo->set_theme($this->request('theme'));
        $doVideo->set_title($title);
        $doVideo->set_is_test($this->request('is_test'));
        $doVideo->set_课堂人数上限($this->request('课堂人数上限'));
        $doVideo->set_开始时间($stime);
        $doVideo->set_结束时间($etime);
        $doVideo->set_视频url($this->request('url'));
        $doVideo->set_简介($this->request('简介'));
        $doVideo->set_详情($content);
        $doVideo->set_讲课专家id($expertId);
        $doVideo->set_type('视频');
        $doVideo->set_chatId($chatId);
        $sign_id && $doVideo->set_sign_id($sign_id);
        $re1 = $doVideo->save();

        #添加报名
        $courseId = $doVideo->get_id();
        $dosignUp = new Do语音课程报名();
        $dosignUp->set_专家('是');
        $dosignUp->set_课程id($courseId);
        $dosignUp->where($dosignUp->data)->row();
        $dosignUp->set_用户id($expertId);
        $res2 = $dosignUp->save();

        if ($groupId && $re1 && $res2) {
            pdo()->commit();
            $msg = ($id) ? '修改成功' : '添加成功';
            $url = $this->url('video_course','index');
            $this->successPage($msg, $url);
        } else {
            $msg = ($id) ? '修改失败' : '添加失败';
            pdo()->rollBack();
            $this->errorPage($msg);
        }

    }
    //创建课程群
    public function create_course_group($expertId)
    {
        $doUser = new Do用户();
        $doUser->set_id($expertId);
        $openId = $doUser->fields('openID')->where($doUser->data)->getOneField();
        $dataCenter = new CUI数据中心('video_course',$openId);
        $cUser = new C用户($dataCenter->vo信息中心);
        //3表示群的类型为视频课程
        return $cUser->fc创建课程群组($expertId,3);
    }
    //搜索用户
    public function find_user(){
        $doUser = new Do用户();
        $doDoctor = new Do医师详情();
        $name = $this->request('name');
        $where = '公众号ID='.G_SERV_ID;
        $result = '';
        if(!$name) {
           exit('');
        }
        $where.=" and a.name like '%".$name."%'";
        $users = $doUser->fields("a.id,a.name,b.医院")
            ->leftJoin($doDoctor,'b','a.id=b.用户id')
            ->where($where)
            ->orderby("a.id desc")->rows();
        foreach($users as $value){
            $result.= "<input type='radio' name='专家id' value='".$value['id']."'>".$value['name']."(".$value['医院'].")&nbsp;";
        }

        echo $result;
    }
    //课程报名人员详情
    public function focus_user_detail(){
        $doSignUp = new Do语音课程报名();
        $courseId = $this->request('id','',true);
        $doUser = new Do用户();
        $doDoctor = new Do医师详情();
        $count = $doSignUp->fields('count(b.id)')->leftJoin($doUser,'b','a.用户id=b.id')
            ->where("a.课程id=".$courseId." and a.状态='报名'")
            ->getOneField();
        $page = new \tools\Page($count,15);

        $doUser = new Do用户();
        $users = $doUser->fields('a.*,c.医院')
            ->leftJoin($doSignUp,'b','b.用户id=a.id')
            ->leftJoin($doDoctor,'c','b.用户id=c.用户id')
            ->offset($page->limit)
            ->limit($page->pagesize)
            ->where("b.课程id=".$courseId." and b.状态='报名'")
            ->orderby('a.id desc')
            ->rows();
        require $this->template;

    }
    //修改课程状态
    public function update_course_status(){
        $doVideo = new Do语音课程();
        $id = $this->request('课程id','',true);
        $status = $this->request('状态');
        $course = $doVideo->loadById($id);
        if($course)
        {
            $doVideo->set_id($id);
            $doVideo->set_状态($status);
            $res = $doVideo->save();

            //发送课程相关消息
            $title = $doVideo->get_title();
            //阅读量
            $read_num = $doVideo->get_浏览次数();
            $doSignUp = new Do语音课程报名();
            //报名人数
            $sign_up_num = $doSignUp->where("课程id=".$id." and 状态='报名'")->count();

            $doGroup = new Do群离线();
            //在线人数
            $online_num = $doGroup->where("群id=".$doVideo->get_群id())->count();

            $doComment = new DoStatistic();
            //阅读人数
            $reader_num = $doComment->where("type=2 and tid=".$id)->count();
            $content = "课程《".$title."》".$status."上课时的报名人数：".$sign_up_num."，在线听课人数：".$online_num."，阅读人数：".$reader_num."，阅读量：".$read_num;

            $send = new automation();
            foreach($send->phones as $v){
                $send->send_text_messages($content, $v);
            }
            echo $res;
        }
        return;
    }


    //推送视频课程
    public function send_course(){
        $bm = new C发微信消息();
        $courseId = $this->request('id','',true);
        $openId = $this->request('oid');
        if(!$openId){
            $doVideo = new Do语音课程();
            $doVideo->set_id($courseId);
            $doVideo->set_发送('已发送');
            $doVideo->save();
        }

        if ($openId) {
            $bm->fc发送图文消息_所有用户('视频课程', $courseId, $openId);
        } else {
            $this->run_cli('courser_msg', $courseId);
        }
        echo 1;
    }

    //给已报名用户推送课前提醒
    public function push_before_class(){
        $bm = new C发微信消息();
        $courseId = $this->request('id','',true);
        $bm->f推送单个课程消息($courseId);
        echo true;
    }
    //在线人信息统计
    public function show_online_user(){
        // type:1、在线人数总计，2、实时在线人数
        $type = $this->request("type");
        $groupId = $this->request("gid");
        $doGroup = new Do群离线();
        if($type == 1){
            $where = "群id = ".$groupId;
        }else{
            $time = date("Y-m-d H:i:s", time()-10);
            $where = "群id = ".$groupId." and 最后在线时间 > '$time'";
        }
        $count = $doGroup->where($where)->count();
        $page = new \tools\Page($count, 15);
        $users = $doGroup->where($where)
            ->offset($page->limit)
            ->limit($page->pagesize)
            ->orderby("time_length desc")
            ->rows();
        foreach($users as $k=>$v){
            $doUser = new Do用户();
            $doDoctor = new Do医师详情();
            $name = $doUser->fields("name")->row($v['用户id'])->data;
            $hospital = $doDoctor->fields("医院")->where("用户id = ".$v['用户id'])->row()->data;
            $users[$k]['time_length'] = ceil($v['time_length']/60);
            $users[$k]['name'] = $name['name'];
            $users[$k]['hospital'] = $hospital['医院'];
        }
       require_once $this->template;
    }
    //人员听课频率统计
    public function frequency_count(){
        $doCourse = new Do语音课程();
        $doUser = new Do用户();
        $groups = $doCourse->fields("群id")->where("群id != ''")->rows();
        $groupIds = [];
        foreach($groups as $v){
           $groupIds[] = $v['群id'];
        }
        $groupId = implode(',', $groupIds);
        $doGroup = new Do群离线();
        $doDoctor = new Do医师详情();
        $num = pdo()->selectOne("select count(t.counts) num from
        (select count(用户id) counts from 群离线 where 用户id!='' and 群id in(".$groupId.") group by 用户id) t");
        $count = $num['num'];
        $page = new \tools\Page($count, 15);
        $users = $doGroup->fields("用户id, count(用户id) course_num, max(最后在线时间) last_time")->where("用户id!='' and 群id in(".$groupId.")")
            ->offset($page->limit)
            ->limit($page->pagesize)
            ->groupby("用户id")
            ->orderby("course_num desc")
            ->rows();
        foreach($users as $k=>$v){
            $doctor = $doDoctor->fields("name, 医院, 职务, 专业领域")
                ->where("用户id = ".$v['用户id'])
                ->row()->data;
            $users[$k]['name'] = $doctor['name'];
            $users[$k]['hospital'] = $doctor['医院'];
            $users[$k]['resign'] = $doctor['职务'];
            $users[$k]['field'] = $doctor['专业领域'];
            $users[$k]['phone'] = $doUser->fields("telephone")->where(array('id'=>$v['用户id']))->getOneField();
        }
        require $this->template;

    }


}